package TDengineDB

import (
	"fmt"
	"reflect"
	"strconv"
	"sync"
	"time"
)

//索引记录
var indexMap = make(map[string]bool)

//锁
var look sync.Mutex

//获取客户端
func GetTDengineClient(config map[string]string) *TDengineClient {
	ipport := config["ipport"]
	username := config["username"]
	password := config["password"]
	timeout := time.Second * 30
	if timeoutStr, ok := config["timeout"]; ok {
		atoi, err := strconv.Atoi(timeoutStr)
		if err == nil {
			timeout = time.Second * time.Duration(atoi)
		}
	}
	return NewTDengineClient(ipport, username, password, timeout)
}

//添加映射
// @client 连接对象
// @dataName 数据库名
func DataBaseMapping(client *TDengineClient,config map[string]string) *TDengineContent {
	dbname := config["dbname"]

	return &TDengineContent{
		client:   client,
		database: dbname,
		dbUrl:    fmt.Sprint(client.url, "#", dbname),
	}
}

//数据库上下文
type TDengineContent struct {
	client   *TDengineClient //客户端
	database string          //数据库名称
	dbUrl    string          //数据库rusfurl地址
}

//是否创建数据库（false:不创建）
func (t *TDengineContent) IsCreateDatabase() bool {
	_, ok := indexMap[t.dbUrl]
	if !ok {
		look.Lock()
		defer look.Unlock()

		_, ok := indexMap[t.dbUrl]
		if ok {
			return  false
		}
		indexMap[t.dbUrl] = true
		return true
	}
	return false
}

//是否创建超级表（false:不创建）
func (t *TDengineContent) IsCreateTable(entity interface{}) bool {
	var key string
	typeOfCat := reflect.TypeOf(entity)
	if typeOfCat.Kind() == reflect.Ptr {
		key = fmt.Sprint(t.dbUrl ,"#", typeOfCat.Elem().Name())
	}else {
		key = fmt.Sprint(t.dbUrl, "#", typeOfCat.Name())
	}
	_, ok := indexMap[key]
	if !ok {
		look.Lock()
		defer look.Unlock()

		_, ok := indexMap[key]
		if ok {
			return  false
		}
		indexMap[key] = true
		return true
	}
	return false
}

//获取集合仓储
// entity 结构体,columnModel列模型（"Beijng.Chaoyang", 2）
// INSERT INTO d1001 USING METERS TAGS ("Beijng.Chaoyang", 2) VALUES (now, 10.2, 219, 0.32);
func (t *TDengineContent) GetTDengineRepository(entity interface{}) ITDengineRepository {
	var entityName string
	typeOfCat := reflect.TypeOf(entity)
	if typeOfCat.Kind() == reflect.Ptr {
		entityName = typeOfCat.Elem().Name()
	}else {
		entityName = typeOfCat.Name()
	}
	return &TDengineRepository{
		database:       t.database,
		superTableName: entityName,
		client:         t.client,
	}
}
